/*
 * Copyright 2002-2021 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.context.annotation;

import java.io.IOException;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.aop.framework.AopInfrastructureBean;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.context.event.EventListenerFactory;
import org.springframework.core.Conventions;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.annotation.Order;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;

/**
 * Utilities for identifying {@link Configuration} classes.
 *
 * @author Chris Beams
 * @author Juergen Hoeller
 * @author Sam Brannen
 * @since 3.1
 */
abstract class ConfigurationClassUtils {

	//TODO class如果是@Configuration标注的类，那么将属性标准为full
	public static final String CONFIGURATION_CLASS_FULL = "full";
	//TODO 非@Configuration标注的类，属性标注为lite
	public static final String CONFIGURATION_CLASS_LITE = "lite";
	//TODO org.springframework.context.annotation.ConfigurationClassPostProcessor.configurationClass作为属性配置类型标记属性的key
	public static final String CONFIGURATION_CLASS_ATTRIBUTE =
			Conventions.getQualifiedAttributeName(ConfigurationClassPostProcessor.class, "configurationClass");

	//TODO org,springframework.context.annotation.ConfigurationClassPostProcessor.order配置属件配置类排序的属性ke
	private static final String ORDER_ATTRIBUTE =
			Conventions.getQualifiedAttributeName(ConfigurationClassPostProcessor.class, "order");


	private static final Log logger = LogFactory.getLog(ConfigurationClassUtils.class);
	//TODO 定义set集合，用于存储标注配置类注解
	private static final Set<String> candidateIndicators = new HashSet<>(8);

	static {
		candidateIndicators.add(Component.class.getName());
		candidateIndicators.add(ComponentScan.class.getName());
		candidateIndicators.add(Import.class.getName());
		candidateIndicators.add(ImportResource.class.getName());
	}


	/**
	 * Check whether the given bean definition is a candidate for a configuration class
	 * (or a nested component class declared within a configuration/component class,
	 * to be auto-registered as well), and mark it accordingly.
	 * @param beanDef the bean definition to check
	 * @param metadataReaderFactory the current factory in use by the caller
	 * @return whether the candidate qualifies as (any kind of) configuration class
	 */
	public static boolean checkConfigurationClassCandidate(
			BeanDefinition beanDef, MetadataReaderFactory metadataReaderFactory) {
		//TODO 根据BeanDefinition获取对应的类名称
		String className = beanDef.getBeanClassName();
		//TODO 判断是否为空，为空则直接返回
		if (className == null || beanDef.getFactoryMethodName() != null) {
			return false;
		}
		//TODO 声明AnnotationMetadata变量
		AnnotationMetadata metadata;
		//TODO 【分类处理】根据不同情况获取不同的AnnotationMetadata，获取注解元数据信息
		//TODO 【处理是注解标注的类】判断当前的BeanDefinition是否是注解类型的AnnotatedBeanDefinition
		if (beanDef instanceof AnnotatedBeanDefinition &&
				className.equals(((AnnotatedBeanDefinition) beanDef).getMetadata().getClassName())) {
			// Can reuse the pre-parsed metadata from the given BeanDefinition...
			//TODO 从当前bean的定义信息中获取元数据信息
			metadata = ((AnnotatedBeanDefinition) beanDef).getMetadata();
		}
		//TODO 判断是否是spring中默认的BeanDefinition,有一些类会直接继承AbstractBeanDefinition,
		// 一般情况下，没有注解标注的类 beanDef instanceof AbstractBeanDefinition返回true,但是 ((AbstractBeanDefinition) beanDef).hasBeanClass()返回false，
		// 因为Class类是final修饰的，不会有子类进行实现或继承，所以一般也不会进入
		else if (beanDef instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) beanDef).hasBeanClass()) {
			// Check already loaded Class if present...
			// since we possibly can't even load the class file for this Class.
			// TODO 检查已经加载的类是否存在…
			//TODO 获取当前bean对象的的class对象
			Class<?> beanClass = ((AbstractBeanDefinition) beanDef).getBeanClass();
			//TODO 如果class实例是下面四种类或者接口的子类，父接口等任何一种情况，直接返回
			if (BeanFactoryPostProcessor.class.isAssignableFrom(beanClass) ||
					BeanPostProcessor.class.isAssignableFrom(beanClass) ||
					AopInfrastructureBean.class.isAssignableFrom(beanClass) ||
					EventListenerFactory.class.isAssignableFrom(beanClass)) {
				return false;
			}
			//TODO 为给定的类创建新的AnnotationMetadata实例
			metadata = AnnotationMetadata.introspect(beanClass);
		}
		//TODO 【处理不是注解标注的类】说明不是使用注解标注的bean
		else {
			try {
				//TODO 根据className获取MetadataReader实例,真正的实现类为SimpleMetadataReader，包含resource属性和annotationMetadata属性
				MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(className);
				//TODO 读取底层类的完整注释元数据，包括带注解方法的元数据，获取annotationMetadata属性值，普通的bean也会有annotationMetadata属性值
				metadata = metadataReader.getAnnotationMetadata();
			}
			catch (IOException ex) {
				if (logger.isDebugEnabled()) {
					logger.debug("Could not find class file for introspecting configuration annotations: " +
							className, ex);
				}
				return false;
			}
		}
		//TODO 判断当前的注解的元数据信息是不是有@Configuration注解修饰，如果不是注解标注的则为null
		Map<String, Object> config = metadata.getAnnotationAttributes(Configuration.class.getName());
		//TODO 如果是@Configuration注解修饰，config不为空并且config.get("proxyBeanMethods")为false（是否使用了代理模式），且将bean的标记为full
		if (config != null && !Boolean.FALSE.equals(config.get("proxyBeanMethods"))) {
			//TODO 设置属性值   CONFIGURATION_CLASS_FULL---》将bean的定义标记为full
			beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_FULL);
		}
		//TODO config.get("proxyBeanMethods")或者被@Component,@ComponentScan @Import @ImportResource标注，将bean的定义标记为lite 查看源码可以看出
		else if (config != null || isConfigurationCandidate(metadata)) {
			//TODO 如果是非@Configuration注解修饰 CONFIGURATION_CLASS_LITE---》将bean的定义标记为lite
			beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_LITE);
		}
		else {
			return false;
		}

		// It's a full or lite configuration candidate... Let's determine the order value, if any.
		//TODO bean定义是一个标记为full或者lite的候选项，如果设置order则设置order属性值
		Integer order = getOrder(metadata);
		//TODO 如果值不为空的话，那么直接设置值到具体的BeanDefinition
		if (order != null) {
			//TODO 设置bean定义的order值
			beanDef.setAttribute(ORDER_ATTRIBUTE, order);
		}

		return true;
	}

	/**
	 * Check the given metadata for a configuration class candidate
	 * (or nested component class declared within a configuration/component class).
	 * @param metadata the metadata of the annotated class
	 * @return {@code true} if the given class is to be registered for
	 * configuration class processing; {@code false} otherwise
	 */
	public static boolean isConfigurationCandidate(AnnotationMetadata metadata) {
		// Do not consider an interface or an annotation...
		//TODO 不考虑接口或注释……
		if (metadata.isInterface()) {
			return false;
		}

		// Any of the typical annotations found?
		//TODO 检查是否为注解@Component,@ComponentScan @Import @ImportResource标注
		//TODO candidateIndicators集合可以看出
		for (String indicator : candidateIndicators) {
			if (metadata.isAnnotated(indicator)) {
				return true;
			}
		}

		// Finally, let's look for @Bean methods...
		//TODO 最后检查是否被@Bean标注的方法
		return hasBeanMethods(metadata);
	}

	static boolean hasBeanMethods(AnnotationMetadata metadata) {
		try {
			return metadata.hasAnnotatedMethods(Bean.class.getName());
		}
		catch (Throwable ex) {
			if (logger.isDebugEnabled()) {
				logger.debug("Failed to introspect @Bean methods on class [" + metadata.getClassName() + "]: " + ex);
			}
			return false;
		}
	}

	/**
	 * Determine the order for the given configuration class metadata.
	 * @param metadata the metadata of the annotated class
	 * @return the {@code @Order} annotation value on the configuration class,
	 * or {@code Ordered.LOWEST_PRECEDENCE} if none declared
	 * @since 5.0
	 */
	@Nullable
	public static Integer getOrder(AnnotationMetadata metadata) {
		Map<String, Object> orderAttributes = metadata.getAnnotationAttributes(Order.class.getName());
		return (orderAttributes != null ? ((Integer) orderAttributes.get(AnnotationUtils.VALUE)) : null);
	}

	/**
	 * Determine the order for the given configuration class bean definition,
	 * as set by {@link #checkConfigurationClassCandidate}.
	 * @param beanDef the bean definition to check
	 * @return the {@link Order @Order} annotation value on the configuration class,
	 * or {@link Ordered#LOWEST_PRECEDENCE} if none declared
	 * @since 4.2
	 */
	public static int getOrder(BeanDefinition beanDef) {
		Integer order = (Integer) beanDef.getAttribute(ORDER_ATTRIBUTE);
		return (order != null ? order : Ordered.LOWEST_PRECEDENCE);
	}

}
